<template>
  <div>
    <h1>活动列表</h1>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入活动名称"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadActiveList()">查询</el-button>
          <el-button type="success" @click="onAddActive()">添加活动</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table :data="activeData" border style="width: 100%">
        <el-table-column prop="activeId" label="活动Id" />
        <el-table-column prop="activeName" label="活动名称" />
        <el-table-column prop="beginTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="flagName" label="参与用户" />
        <el-table-column prop="payScore" label="支付" />
        <el-table-column prop="freeTimes" label="活动免费抽奖次数" />
        <el-table-column prop="typeName" label="类型" />
        <el-table-column prop="winName" label="中奖名单" />
        <el-table-column prop="recordName" label="中奖记录" />
        <el-table-column prop="activeStatus" label="活动状态">
          <template #default="scope">
            <span v-if="scope.row.activeStatus == 0">开启</span>
            <span v-if="scope.row.activeStatus == 1">关闭</span>
          </template>
        </el-table-column>
        <el-table-column prop="activeContent" label="活动简介">
          <template #default="scope">
            <div v-html="scope.row.activeContent"></div>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="updateById(scope.row)"
              >修改</el-button
            >
            <el-button type="danger" @click="deleteById(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="活动添加" width="1000">
        <el-form :model="form" :rules="rules" ref="ruleFormRef">
          <el-form-item
            label="活动名称"
            prop="activeName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.activeName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="开始时间"
            prop="beginTime"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              v-model="form.beginTime"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="结束时间"
            prop="endTime"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="参与用户"
            prop="userFlag"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.userFlag" placeholder="请选择参与用户">
              <el-option
                v-for="item in flagData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="支付"
            prop="payScore"
            :label-width="formLabelWidth"
          >
            <el-input-number v-model="form.payScore" :min="1" />
          </el-form-item>
          <el-form-item
            label="活动免费抽奖次数"
            prop="freeTimes"
            :label-width="formLabelWidth"
          >
            <el-input-number v-model="form.freeTimes" :min="1" />
          </el-form-item>
          <el-form-item
            label="类型"
            prop="winType"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.winType" placeholder="请选择类型">
              <el-option
                v-for="item in typeData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="中奖名单"
            prop="winFlag"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.winFlag" placeholder="请选择中奖名单">
              <el-option
                v-for="item in winData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="中奖记录"
            prop="winRecord"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.winRecord" placeholder="请选择记录">
              <el-option
                v-for="item in recordData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="活动状态"
            prop="activeStatus"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.activeStatus" placeholder="请选择活动状态">
              <el-option label="开启" :value="0" />
              <el-option label="关闭" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="活动规则"
            prop="activeContent"
            :label-width="formLabelWidth"
          >
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="form.activeContent"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        v-model="dialogUpdateFormVisible"
        title="活动修改"
        width="1000"
      >
        <el-form :model="form" :rules="rules" ref="ruleFormRef">
          <el-form-item label="活动名称" :label-width="formLabelWidth">
            <el-input
              disabled="disabled"
              v-model="form.activeName"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="开始时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.beginTime"
              disabled="disabled"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.endTime"
              disabled="disabled"
              type="datetime"
              placeholder="请选择结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="参与用户" :label-width="formLabelWidth">
            <el-select v-model="form.userFlag" placeholder="请选择参与用户">
              <el-option
                v-for="item in flagData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="支付" :label-width="formLabelWidth">
            <el-input-number v-model="form.payScore" :min="1" />
          </el-form-item>
          <el-form-item label="活动免费抽奖次数" :label-width="formLabelWidth">
            <el-input-number v-model="form.freeTimes" :min="1" />
          </el-form-item>
          <el-form-item label="类型" :label-width="formLabelWidth">
            <el-select v-model="form.winType" placeholder="请选择类型">
              <el-option
                v-for="item in typeData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="中奖名单" :label-width="formLabelWidth">
            <el-select v-model="form.winFlag" placeholder="请选择中奖名单">
              <el-option
                v-for="item in winData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="中奖记录" :label-width="formLabelWidth">
            <el-select v-model="form.winRecord" placeholder="请选择记录">
              <el-option
                v-for="item in recordData"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="活动状态" :label-width="formLabelWidth">
            <el-select v-model="form.activeStatus" placeholder="请选择活动状态">
              <el-option label="开启" :value="0" />
              <el-option label="关闭" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="活动规则" :label-width="formLabelWidth">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="form.activeContent"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogUpdateFormVisible = false">取消</el-button>
            <el-button type="primary" @click="updateByActiveId()">
              修改
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getActiveList,
  addActive,
  updateActive,
  deleteByActiveId,
  getDictList,
} from "../api/api";
import { ElMessage } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const activeData = ref([]);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});
const total = ref(0);
const dialogFormVisible = ref(false);
const dialogUpdateFormVisible = ref(false);
const formLabelWidth = "140px";

const form = ref({
  activeId: null,
  activeContent: "",
  activeName: "",
  activeStatus: null,
  beginTime: "",
  createBy: "",
  createTime: "",
  endTime: "",
  freeTimes: null,
  payScore: null,
  userFlag: null,
  winFlag: null,
  winRecord: null,
  winType: null,
});
//删除
const deleteById = (row: any) => {
  deleteByActiveId(row.activeId).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      loadActiveList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
//修改
const updateById = (row: any) => {
  Object.assign(form.value, row);
  dialogUpdateFormVisible.value = true;
};
const updateByActiveId = () => {
  updateActive(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      dialogUpdateFormVisible.value = false;
      loadActiveList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
const rules = ref<FormRules>({
  activeName: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  activeContent: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  activeStatus: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  beginTime: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  createTime: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  endTime: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  freeTimes: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  payScore: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  userFlag: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  winFlag: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  winRecord: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  winType: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
});
//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addActive(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadActiveList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const mode = ref("default");
// 内容 HTML
const valueHtml = ref("<p>hello</p>");

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

//添加活动
const onAddActive = () => {
  form.value = {
    activeId: null,
    activeContent: "",
    activeName: "",
    activeStatus: null,
    beginTime: "",
    createBy: "",
    createTime: "",
    endTime: "",
    freeTimes: null,
    payScore: null,
    userFlag: null,
    winFlag: null,
    winRecord: null,
    winType: null,
  };
  dialogFormVisible.value = true;
};
//查询列表
const loadActiveList = () => {
  getActiveList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      activeData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadActiveList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadActiveList();
};
const flagData = ref([]);
const typeData = ref([]);
const winData = ref([]);
const recordData = ref([]);
onMounted(() => {
  getDictList(5).then((res) => {
    if (res.data.code == 200) {
      flagData.value = res.data.data;
    }
  });
  getDictList(6).then((res) => {
    if (res.data.code == 200) {
      typeData.value = res.data.data;
    }
  });
  getDictList(7).then((res) => {
    if (res.data.code == 200) {
      winData.value = res.data.data;
    }
  });
  getDictList(8).then((res) => {
    if (res.data.code == 200) {
      recordData.value = res.data.data;
    }
  });
  loadActiveList();
});
</script>

<style scoped></style>
